﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using QuizzMe.Helpers;
using QuizzMe.Model;
using QuizzMe.QuizzServiceRef;

namespace QuizzMe.Pages
{
    /// <summary>
    /// Theme choice page
    /// </summary>
    public partial class Themes : BasePage
    {
        private readonly List<Theme> _themeSource;
        private readonly ObservableCollection<CheckableText> _themeList;

        public ObservableCollection<CheckableText> ThemeList
        {
            get { return _themeList; }
        }

        public Themes()
        {
            _themeSource = new List<Theme>();
            _themeList = new ObservableCollection<CheckableText>();

            QuizzServiceClient client = new QuizzServiceClient();
            client.GetThemesCompleted += (o, args) =>
                                             {
                                                 foreach (Theme theme in args.Result)
                                                 {
                                                     _themeSource.Add(theme);
                                                     _themeList.Add(new CheckableText(theme.name));
                                                 }
                                                 Loading = false;
                                             };
            Loading = true;
            client.GetThemesAsync();

            InitializeComponent();
        }

        /// <summary>
        /// Save the selected theme and start a quizz
        /// </summary>
        private void ButtonSaveClick(object sender, RoutedEventArgs e)
        {
            CheckableText checkableText = _themeList.FirstOrDefault(c => c.Selected);
            if (checkableText != null)
            {
                IEnumerable<Theme> selectedThemes = _themeSource.Where(t => t.name.Equals(checkableText.Text));
                if (selectedThemes.Count() > 0)
                {
                    Theme selectedTheme = selectedThemes.First();

                    System.Windows.Browser.HtmlPage.Document.QueryString["theme"] = selectedTheme.themeId.ToString();
                    this.NavigateTo(new Uri("/Quizz?theme=" + selectedTheme.themeId, UriKind.Relative));
                    return;
                }
            }

            this.NavigateTo(new Uri("/Home", UriKind.Relative));
        }

        private void ButtonCancelClick(object sender, RoutedEventArgs e)
        {
            this.NavigateTo(new Uri("/Home", UriKind.Relative));
        }
    }
}
